//
//  HMStatusListViewModel.swift
//  iOSWeibo12
//
//  Created by Admin on 16/9/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

/// 处理 HMStatus 相关操作,添加 loadStatus 方法来加载微博数据
class HMStatusListViewModel: NSObject {
    
    static let shared: HMStatusListViewModel = HMStatusListViewModel()
    
    /// 标记是否正在获取微博数据
    private var isLoadingStatus = false
    
    /**
     加载微博数据
     */
    func loadStatus(since_id: Int, max_id: Int, completion: @escaping ([HMStatusViewModel]?, Error?) -> Void) {
        
        if isLoadingStatus {
            let error = NSError(domain: "cn.itheima.com", code: -1, userInfo: ["原因" : "同时加载数据了"])
            completion(nil, error)
            return
        }
        
        isLoadingStatus = true
        
        HMStatusDAL.shared.loadStatus(since_id: since_id, max_id: max_id) { (array, error) in
            // 从网络加载微博数据完成
            self.isLoadingStatus = false
            
            if error != nil {
                print("出错了 \(error)")
                completion(nil, error)
                return
            }
            
            DispatchQueue.global().async(execute: {
                // 定义空数组保存模型数据
                var statusVMs = [HMStatusViewModel]()
                
                // 1遍历数组字典转模型
                for dict in array! {
                    let status = HMStatus(dict: dict)
                    
                    let statusVM = HMStatusViewModel(status: status)
                    statusVMs.append(statusVM)
                }
                
                DispatchQueue.main.async(execute: {
                    completion(statusVMs, nil)
                })
            })
        }
    }
    
    /**
     发布微博, 连续两次发布的微博不可以重复
     parameter status:             微博内容
     parameter sendStatusCallBack: 回调
     */
    func sendStatus(status: String, image: UIImage?, sendStatusCallBack: @escaping (Error?) -> ()) {
        // 判断token
        guard let access_token = HMUserAccountViewModel.shared.userAccount?.access_token else {
            print("token为空")
            return
        }
        
        // 参数
        let parameters = [
            "access_token": access_token,
            "status": status
        ]
        
        if let image = image {
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            HMNetworkTool.shared.requestPost(URLString: urlString, parameters: parameters, constructingBodyWith: { (formData) in
                // 将图片转成NSData
                let imageData = UIImagePNGRepresentation(image)!
                
                // data: 要上传内容的2进制
                // name: 接口文档指定的上传字段名称
                // fileName: 保存在服务器的文件名称,看api文档,有规定有按规定来填,没有规定,随便填
                // mimeType: 类型: image/png. image/jpeg, image/gif
                formData.appendPart(withFileData: imageData, name: "pic", fileName: "hehe", mimeType: "image/png")
                }, progress: nil, success: { (_, result) in
                    sendStatusCallBack(nil)
                }, failure: { (_, error) in
                    sendStatusCallBack(error)
            })
        } else {
            // 没有图片
            // url
            let urlString = "https://api.weibo.com/2/statuses/update.json"
            
            // 发送请求
            HMNetworkTool.shared.request(method: .POST, URLString: urlString, parameters: parameters, progress: nil, success: { (_, result) in
                sendStatusCallBack(nil)
                }, failure: { (_, error) in
                sendStatusCallBack(error)
            })
        }
    }
    
}
